package com.lianyu.wangyiyun.utils;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.HashMap;
import java.util.Map;

import static android.content.Context.MODE_PRIVATE;

/**
 * 登录信息管理类
 *
 * @author Chen Yuguang
 * @date 2021/5/7 3:44
 */
public class LoginManager {

    private static SharedPreferences loginPreference;

    /**
     * 初始化登录信息储存库
     *
     * @param context 需要获取库的内容
     * @author Chen Yuguang
     * @date 2021/5/7 3:41
     */
    public static void initLogin(Context context) {
        if (loginPreference == null) {
            loginPreference = context.getSharedPreferences("login", MODE_PRIVATE);
        }
    }

    /**
     * 读登录信息
     *
     * @author Chen Yuguang
     * @date 2021/5/7 3:18
     */
    public static Map<String, String> readLogin() {
        Map<String, String> m = new HashMap<>(2);
        String account = loginPreference.getString("account", "");
        String password = loginPreference.getString("password", "");
        m.put("account", account);
        m.put("password", password);
        return m;
    }

    /**
     * 获取是否记住密码
     *
     * @author Chen Yuguang
     * @date 2021/5/7 4:50
     */
    public static Boolean getChecked() {
        return loginPreference.getBoolean("checked", true);
    }

    /**
     * 写登录信息
     *
     * @param checked  是否记住密码
     * @param account  账号
     * @param password 密码
     * @author Chen Yuguang
     * @date 2021/5/7 3:14
     */
    public static void configLoginInfo(final boolean checked, final String account, final String password) {
        SharedPreferences.Editor editor = loginPreference.edit();
        editor.putBoolean("checked", checked);
        if (checked) {
            editor.putString("account", account);
            editor.putString("password", password);
        } else {
            editor.remove("account").remove("password");
        }
        editor.apply();
    }
}
